﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Derbster.Domain;

namespace Derbster.Data
{
    /// <summary>
    /// This is an in-memory version of repository. Note, we don't use the singleton pattern here. 
    /// Instead, we count on Unity to control the lifecycle of these objects. By default, we use
    /// a container-controlled lifecycle, so only one instance of a repository is returned per container.
    /// </summary>
    public class DbSkaterRepository : ISkaterRepository, IDisposable
    {
        private readonly DerbsterDbContext _dbContext;

        public DbSkaterRepository()
        {
            _dbContext = new DerbsterDbContext();
        }

        public Skater Create(string name, string number)
        {
            Skater newSkater = new Skater(name,number);
            _dbContext.Skaters.Add(newSkater);
            _dbContext.SaveChanges();

            return newSkater;
        }

        public Skater FindById(int id)
        {
            return _dbContext.Skaters.SingleOrDefault(m => m.SkaterId == id);
        }

        public Skater FindByName(string name)
        {
            return _dbContext.Skaters.SingleOrDefault(m => m.Name.ToLower() == name.ToLower());
        }

        public Skater Update(Skater official)
        {
            _dbContext.SaveChanges();
            return official;
        }

        public void Delete(Skater official)
        {
            _dbContext.Skaters.Remove(official);
            _dbContext.SaveChanges();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing && _dbContext != null)
                _dbContext.Dispose();
        }

        public IEnumerator<Skater> GetEnumerator()
        {
            return _dbContext.Skaters.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public Expression Expression
        {
            get
            {
                return _dbContext.Skaters.Expression;
            }
        }

        public Type ElementType
        {
            get
            {
                return _dbContext.Skaters.ElementType;
            }
        }

        public IQueryProvider Provider
        {
            get
            {
                return _dbContext.Skaters.Provider;
            }
        }
    }
}
